package com.dengxian.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dengxian.usercenter.annotation.AuthCheck;
import com.dengxian.usercenter.common.BaseResponse;
import com.dengxian.usercenter.common.ErrorCode;
import com.dengxian.usercenter.common.ResultUtils;
import com.dengxian.usercenter.constant.CommonConstant;
import com.dengxian.usercenter.exception.BusinessException;
import com.dengxian.usercenter.model.domain.Notice;
import com.dengxian.usercenter.model.domain.Report;
import com.dengxian.usercenter.model.domain.User;
import com.dengxian.usercenter.model.dto.DeleteRequest;
import com.dengxian.usercenter.model.dto.NoticeAddRequest;
import com.dengxian.usercenter.model.dto.NoticeQueryRequest;
import com.dengxian.usercenter.model.dto.NoticeUpdateRequest;
import com.dengxian.usercenter.service.NoticeService;
import com.dengxian.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 公告接口
 */
@RestController
@RequestMapping("/notice")
@Slf4j
public class NoticeController {
    @Resource
    private NoticeService noticeService;

    @Resource
    private UserService userService;

    /**
     * 创建
     * @param noticeAddRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/add")
    public BaseResponse<Long> addNotice(@RequestBody NoticeAddRequest noticeAddRequest, HttpServletRequest request) {
        if(noticeAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeAddRequest, notice);
        noticeService.validNotice(notice, true);
        User loginUser = userService.getLoginUser(request);
        notice.setUserId(loginUser.getId());
        boolean result = noticeService.save(notice);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newNoticeId = notice.getId();
        return ResultUtils.success(newNoticeId);
    }

    /**
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteNotice(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Notice oldNotice = noticeService.getById(id);
        if (oldNotice == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean b = noticeService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param noticeUpdateRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/update")
    public BaseResponse<Boolean> updateNotice(@RequestBody NoticeUpdateRequest noticeUpdateRequest, HttpServletRequest request) {
        if (noticeUpdateRequest == null ||  noticeUpdateRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeUpdateRequest, notice);
        noticeService.validNotice(notice, false);
        long id =noticeUpdateRequest.getId();
        // 判断是否存在
        Notice oldNotice = noticeService.getById(id);
        if (oldNotice == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean result = noticeService.updateById(notice);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Notice> getNoticeById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notice notice = noticeService.getById(id);
        return ResultUtils.success(notice);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param noticeQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<Notice>> listNotice(NoticeQueryRequest noticeQueryRequest) {
        Notice noticeQuery = new Notice();
        if (noticeQueryRequest != null) {
            BeanUtils.copyProperties(noticeQueryRequest, noticeQuery);
        }
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>(noticeQuery);
        List<Notice> noticeList = noticeService.list(queryWrapper);
        return ResultUtils.success(noticeList);
    }

    /**
     * 分页获取列表
     *
     * @param noticeQueryRequest
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<Notice>> listNoticeByPage(NoticeQueryRequest noticeQueryRequest) {
        if (noticeQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notice noticeQuery = new Notice();
        BeanUtils.copyProperties(noticeQueryRequest, noticeQuery);
        long current = noticeQueryRequest.getCurrent();
        long size = noticeQueryRequest.getPageSize();
        String sortField = noticeQueryRequest.getSortField();
        String sortOrder = noticeQueryRequest.getSortOrder();
        String content = noticeQuery.getContent();
        String title = noticeQuery.getTitle();
        // content 需支持模糊搜索
        noticeQuery.setContent(null);
        noticeQuery.setTitle(null);
        // 限制爬虫
//        if (size > 50) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>(noticeQuery);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<Notice> noticePage = noticeService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(noticePage);
    }
}
